using Microsoft.EntityFrameworkCore;
using Autofac.Extensions.DependencyInjection;
using Autofac;
using System.Reflection;
using WebApp.App_Code;
using Hangfire;
using Hangfire.MemoryStorage;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System.Data.Common;
using Microsoft.Extensions.FileProviders;

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("Config/app.json");
Console.WriteLine(builder.Configuration.GetValue<string>("weixin"));
// Autofac ����
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
 {
     Assembly assembly = Assembly.Load(ServiceCore.GetAssemblyName());
     builder.RegisterAssemblyTypes(assembly)
        .PropertiesAutowired()
        //.AsImplementedInterfaces()// �޽ӿڵ�ע�뷽ʽ
        .InstancePerDependency();
 });
builder.Services.AddCors(delegate (CorsOptions options)
{
    options.AddPolicy("CorsPolicy", delegate (CorsPolicyBuilder corsBuilder)
    {
        //ָ��url����
        corsBuilder.WithOrigins(builder.Configuration.GetValue<string>("Cors").Split(','));
        //Ĭ�Ͽ���
        corsBuilder.SetIsOriginAllowed((string _) => true).AllowAnyMethod().AllowAnyHeader()
            .AllowCredentials();
    });
});

builder.Services.AddControllers(option =>
    {
        option.Filters.Add<GlobalExceptionFilter>();
    }
).AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //���л�ʱkeyΪ�շ���ʽ
    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
    options.SerializerSettings.ReferenceLoopHandling =  ReferenceLoopHandling.Ignore;//����ѭ������
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDbContext<Application.DataContext>(opt => {
    opt.UseSqlite(builder.Configuration.GetConnectionString("Default"));
});

/// <summary>
/// ��ʼ��Dapper���
/// </summary>
DbProviderFactories.RegisterFactory("Microsoft.Data.Sqlite", Microsoft.Data.Sqlite.SqliteFactory.Instance);
DbComponent.InitDapper(new System.Configuration.ConnectionStringSettings
{
    ConnectionString = builder.Configuration.GetConnectionString("Default"),
    ProviderName = "Microsoft.Data.Sqlite"
});

//����redis��ʹ��
builder.Services.AddSingleton<RedisClient>(_=> RedisClientFactory.GetInstance(builder.Configuration));
//��Redis�ֲ�ʽ����������ӵ�������
builder.Services.AddStackExchangeRedisCache(options =>
    {
        //��������Redis������  Configuration.GetConnectionString("RedisConnectionString")��ȡ������Ϣ�Ĵ�
        options.Configuration = "Redis_6";// Configuration.GetConnectionString("RedisConnectionString");
        //Redisʵ����RedisDistributedCache
        options.InstanceName = "RedisDistributedCache";
    });
//����ע��
//builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());

//ע��Log4Net
builder.Services.AddLogging(cfg =>
{
    //Ĭ�ϵ������ļ�·�����ڸ�Ŀ¼�����ļ���Ϊlog4net.config
    //cfg.AddLog4Net();
    //����ļ�·���������б仯����Ҫ����������·��������
    //��������Ŀ��Ŀ¼�´���һ����Ϊconfig���ļ��У���log4net.config�ļ��������У�������Ϊlog4net.config
    //����Ҫʹ������Ĵ�������������
    cfg.AddLog4Net(new Log4NetProviderOptions()
    {
        Log4NetConfigFileName = "Config/log4net.config",
        Watch = true
    });
});

//����Hangfire����.
builder.Services.AddHangfire(x => x.UseStorage(new MemoryStorage()));
builder.Services.AddHangfireServer();

builder.Services.AddSession();

builder.Services.AddSignalR();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//����Hangfire���
app.UseHangfireDashboard();
RecurringJob.AddOrUpdate("test",() => Console.WriteLine($"{DateTime.Now}������Hangfire������һ����ʱ����ÿ���Ӷ�ʱ���һ��!"), 
    Cron.Minutely());

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
//����www��̬Ŀ¼
app.UseStaticFiles();
//����session
app.UseSession();
//���ÿ���
app.UseCors("CorsPolicy");
//�����ϴ��ļ�Ŀ¼
app.UseStaticFiles(new StaticFileOptions { 
    FileProvider =  new PhysicalFileProvider(builder.Configuration.GetValue<string>("UploadConfig:UploadDir")),
    RequestPath = "/upload/view"
});

app.MapControllers();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<ChatHub>("/chatHub");
});

app.Run();
